# coding: utf-8
import datetime
import re
from copy import deepcopy
from db.mongo import MongoTest



def search_limit(p, mongo, price_start, price_end):
    global food_name_lst
    mts = mongo.find_page("anly_data", p)
    page_plan = []
    if len(mts) == 0:
        return False
    for mt in mts:
        shop_id = str(mt.get("shop_id"))

        shop_name = mt.get("shop_name")
        phone = mt.get("phone_list")[0]
        address = mt.get("address")
        location = str(mt.get("latitude")) + "," + str(mt.get("longitude"))
        print(shop_name + "  - 计算满减")
        if mt.get("shipping_fee_tip") == "免配送费":
            shipping_fee_tip = 0
        else:
            shipping_fee_tip = float(re.findall(r'\d+', mt.get("shipping_fee_tip"))[0])
        min_price_tip = float(re.findall(r'\d+', mt.get("min_price_tip"))[0])
        trade_area = mt.get("trade_area")
        discounts2 = mt.get("discounts2")
        food_spu_tags = mt.get("food_spu_tags")
        discounts = list()
        new_user_reduce_fee = 0
        for activity in discounts2:
            info = activity.get("info")
            if '本店新用户立减' in info:
                new_user_reduce_fee = float(re.findall(r'\d+', info)[0])

        foods_first = [] #8-13元
        foods_second = [] #13-18元
        foods_third = [] #18元以上
        for food_tag in food_spu_tags:
            spus = food_tag.get("spus")
            for food in spus:
                if food.get("skus")[0].get("activity_tag_id", "") == "act_17_17":
                    food_add = {
                        "foodName": food.get("name"),
                        "price": round(food.get("min_price"),2),
                        "boxPrice": round(food.get("skus")[0].get("box_price"),2),
                        "out_of_packet" : round(food.get("min_price") + food.get("skus")[0].get("box_price") - new_user_reduce_fee , 2),
                    }
                    if food.get("min_price") >=8 and food.get("min_price") <= 13:
                        if not food_add in foods_first:
                            foods_first.append(food_add)
                    elif food.get("min_price") > 13 and food.get("min_price") <= 18:
                        if not food_add in foods_first:
                            foods_second.append(food_add)
                    elif food.get("min_price") >18 :
                        if not food_add in foods_first:
                            foods_third.append(food_add)
        for i in range(len(foods_first)):
            for j in range(i + 1, len(foods_first)):
                if foods_first[i].get("price") > foods_first[j].get("price"):
                    temp = deepcopy(foods_first[i])
                    foods_first[i] = deepcopy(foods_first[j])
                    foods_first[j] = temp

        for i in range(len(foods_second)):
            for j in range(i + 1, len(foods_second)):
                if foods_second[i].get("price") > foods_second[j].get("price"):
                    temp = deepcopy(foods_second[i])
                    foods_second[i] = deepcopy(foods_second[j])
                    foods_second[j] = temp

        for i in range(len(foods_third)):
            for j in range(i + 1, len(foods_third)):
                if foods_third[i].get("price") > foods_third[j].get("price"):
                    temp = deepcopy(foods_third[i])
                    foods_third[i] = deepcopy(foods_third[j])
                    foods_third[j] = temp




        page_plan.append(
            {
                "menu" : foods_first,
                "menu_second" : foods_second[:8],
                "menu_third" : foods_third[:5],
                "phone": phone,
                "shop_id": shop_id,
                "new_user_reduce_fee": new_user_reduce_fee,
                "address": address,
                "location": location,
                "shopName": shop_name,
                "min_price_tip": min_price_tip,
                "shipping_fee_tip": shipping_fee_tip,
            }
        )
    return page_plan


if __name__ == '__main__':
    page_count = 0
    mongo = MongoTest()
    plans = list()
    price_start = 8
    price_end = 18

    nowTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    while True:
        print("==第{}页 =================== 累计：{}".format(page_count + 1, (page_count + 1) * 5))
        res = search_limit(page_count, mongo, price_start, price_end)
        if res == False:
            break
        else:
            plans += res
        page_count += 1

    with open("discounts123.txt", "w", encoding="utf-8") as file:
        for plan in plans:
            file.write("**{}\t\t{}********\n".format(plan.get("shopName"),plan.get("address")))
            file.write("\t起送费:{};\t\t配送费:{};\t\t门店新用户立减:{};\n".format(plan.get("min_price_tip"),plan.get("shipping_fee_tip"),plan.get("new_user_reduce_fee")))

            if len(plan.get("menu")) > 0:
                file.write("\t第一档:8~13元**\n")
                for index, food in list(enumerate(plan.get("menu"))):
                    file.write("\t\t{}、{}：{}".format(index + 1 , food.get("foodName") , food.get("price") + food.get("boxPrice")))
                    file.write("\t\t实付:{}\n".format(food.get("out_of_packet")))

            if len(plan.get("menu_second")) > 0:
                file.write("\t第二档:13~18元**\n")
                for index, food in list(enumerate(plan.get("menu_second"))):
                    file.write("\t\t{}、{}：{}".format(index + 1 , food.get("foodName") , food.get("price") + food.get("boxPrice")))
                    file.write("\t\t实付:{}\n".format(food.get("out_of_packet")))

            if len(plan.get("menu_third")) > 0:
                file.write("\t第三档:18元以上**\n")
                for index, food in list(enumerate(plan.get("menu_third"))):
                    file.write("\t\t{}、{}：{}".format(index + 1 , food.get("foodName") , food.get("price") + food.get("boxPrice")))
                    file.write("\t\t实付:{}\n".format(food.get("out_of_packet")))

        file.close()